<?php

use app\common\model\Category;
use fast\Form;
use fast\Tree;
use think\Db;
use think\Loader;

if (!function_exists('build_select')) {

    /**
     * 生成下拉列表
     * @param string $name
     * @param mixed $options
     * @param mixed $selected
     * @param mixed $attr
     * @return string
     */
    function build_select($name, $options, $selected = [], $attr = [])
    {
        $options  = is_array($options) ? $options : explode(',', $options ?? '');
        $selected = is_array($selected) ? $selected : explode(',', $selected ?? '');
        return Form::select($name, $options, $selected, $attr);
    }
}

if (!function_exists('build_radios')) {

    /**
     * 生成单选按钮组
     * @param string $name
     * @param array $list
     * @param mixed $selected
     * @return string
     */
    function build_radios($name, $list = [], $selected = null)
    {
        $html     = [];
        $selected = is_null($selected) ? key($list) : $selected;
        $selected = is_array($selected) ? $selected : explode(',', $selected);
        foreach ($list as $k => $v) {
            $html[] = sprintf(Form::label("{$name}-{$k}", "%s " . str_replace('%', '%%', $v)), Form::radio($name, $k, in_array($k, $selected), ['id' => "{$name}-{$k}"]));
        }
        return '<div class="radio">' . implode(' ', $html) . '</div>';
    }
}

if (!function_exists('build_checkboxs')) {

    /**
     * 生成复选按钮组
     * @param string $name
     * @param array $list
     * @param mixed $selected
     * @return string
     */
    function build_checkboxs($name, $list = [], $selected = null)
    {
        $html     = [];
        $selected = is_null($selected) ? [] : $selected;
        $selected = is_array($selected) ? $selected : explode(',', $selected);
        foreach ($list as $k => $v) {
            $html[] = sprintf(Form::label("{$name}-{$k}", "%s " . str_replace('%', '%%', $v)), Form::checkbox($name, $k, in_array($k, $selected), ['id' => "{$name}-{$k}"]));
        }
        return '<div class="checkbox">' . implode(' ', $html) . '</div>';
    }
}


if (!function_exists('build_category_select')) {

    /**
     * 生成分类下拉列表框
     * @param string $name
     * @param string $type
     * @param mixed $selected
     * @param array $attr
     * @param array $header
     * @return string
     */
    function build_category_select($name, $type, $selected = null, $attr = [], $header = [])
    {
        $tree = Tree::instance();
        $tree->init(Category::getCategoryArray($type), 'pid');
        $categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = $header ? $header : [];
        foreach ($categorylist as $k => $v) {
            $categorydata[$v['id']] = $v['name'];
        }
        $attr = array_merge(['id' => "c-{$name}", 'class' => 'form-control selectpicker'], $attr);
        return build_select($name, $categorydata, $selected, $attr);
    }
}

if (!function_exists('build_toolbar')) {

    /**
     * 生成表格操作按钮栏
     * @param array $btns 按钮组
     * @param array $attr 按钮属性值
     * @return string
     */
    function build_toolbar($btns = null, $attr = [])
    {
        $auth       = \app\admin\library\Auth::instance();
        $controller = str_replace('.', '/', Loader::parseName(request()->controller()));
        $btns       = $btns ? $btns : ['refresh', 'add', 'edit', 'del', 'import'];
        $btns       = is_array($btns) ? $btns : explode(',', $btns);
        $index      = array_search('delete', $btns);
        if ($index !== false) {
            $btns[$index] = 'del';
        }
        $btnAttr = [
            'refresh' => ['javascript:;', 'btn btn-primary btn-refresh', 'fa fa-refresh', '', __('Refresh')],
            'add'     => ['javascript:;', 'btn btn-success btn-add', 'fa fa-plus', __('Add'), __('Add')],
            'edit'    => ['javascript:;', 'btn btn-success btn-edit btn-disabled disabled', 'fa fa-pencil', __('Edit'), __('Edit')],
            'del'     => ['javascript:;', 'btn btn-danger btn-del btn-disabled disabled', 'fa fa-trash', __('Delete'), __('Delete')],
            'import'  => ['javascript:;', 'btn btn-info btn-import', 'fa fa-upload', __('Import'), __('Import')],
        ];
        $btnAttr = array_merge($btnAttr, $attr);
        $html    = [];
        foreach ($btns as $k => $v) {
            //如果未定义或没有权限
            if (!isset($btnAttr[$v]) || ($v !== 'refresh' && !$auth->check("{$controller}/{$v}", $auth->id))) {
                continue;
            }
            list($href, $class, $icon, $text, $title) = $btnAttr[$v];
            //$extend = $v == 'import' ? 'id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"' : '';
            //$html[] = '<a href="' . $href . '" class="' . $class . '" title="' . $title . '" ' . $extend . '><i class="' . $icon . '"></i> ' . $text . '</a>';
            if ($v == 'import') {
                $template = str_replace('/', '_', $controller);
                $download = '';
                if (file_exists("./template/{$template}.xlsx")) {
                    $download .= "<li><a href=\"/template/{$template}.xlsx\" target=\"_blank\">XLSX模版</a></li>";
                }
                if (file_exists("./template/{$template}.xls")) {
                    $download .= "<li><a href=\"/template/{$template}.xls\" target=\"_blank\">XLS模版</a></li>";
                }
                if (file_exists("./template/{$template}.csv")) {
                    $download .= empty($download) ? '' : "<li class=\"divider\"></li>";
                    $download .= "<li><a href=\"/template/{$template}.csv\" target=\"_blank\">CSV模版</a></li>";
                }
                $download .= empty($download) ? '' : "\n                            ";
                if (!empty($download)) {
                    $html[] = <<<EOT
                        <div class="btn-group">
                            <button type="button" href="{$href}" class="btn btn-info btn-import" title="{$title}" id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="{$icon}"></i> {$text}</button>
                            <button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown" title="下载批量导入模版">
                                <span class="caret"></span>
                                <span class="sr-only">Toggle Dropdown</span>
                            </button>
                            <ul class="dropdown-menu" role="menu">{$download}</ul>
                        </div>
EOT;
                } else {
                    $html[] = '<a href="' . $href . '" class="' . $class . '" title="' . $title . '" id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="' . $icon . '"></i> ' . $text . '</a>';
                }
            } else {
                $html[] = '<a href="' . $href . '" class="' . $class . '" title="' . $title . '"><i class="' . $icon . '"></i> ' . $text . '</a>';
            }
        }
        return implode(' ', $html);
    }
}

if (!function_exists('build_heading')) {

    /**
     * 生成页面Heading
     *
     * @param string $path 指定的path
     * @return string
     */
    function build_heading($path = null, $container = true)
    {
        $title = $content = '';
        if (is_null($path)) {
            $action     = request()->action();
            $controller = str_replace('.', '/', Loader::parseName(request()->controller()));
            $path       = strtolower($controller . ($action && $action != 'index' ? '/' . $action : ''));
        }
        // 根据当前的URI自动匹配父节点的标题和备注
        $data = Db::name('auth_rule')->where('name', $path)->field('title,remark')->find();
        if ($data) {
            $title   = __($data['title']);
            $content = __($data['remark']);
        }
        if (!$content) {
            return '';
        }
        $result = '<div class="panel-lead"><em>' . $title . '</em>' . $content . '</div>';
        if ($container) {
            $result = '<div class="panel-heading">' . $result . '</div>';
        }
        return $result;
    }
}

if (!function_exists('zancun')) {
    function zancun($table = 'list_one', $field = 'tong_storage', $prev = "")
    {
//    $table = 'list_one';
//    $field = 'tong_storage';
//    $prev  = '';
        //1、获取本商户的最新进货单号
        $newBillNo = db($table)->field($field)->order($field . ' desc')->find();
        //2、拆分获取到的最新单号字符串
        //3、判断时间是否为今天。若是：时间不变，流水号自增；若不是：时间为今日，流水号置00001。
        //获取当前时间的年月日
        $time = date('Ymd', time());
        if ($newBillNo == null) { //无新纪录
            $zancun = $prev . $time . '00001';
        } else { //有记录
            $billno = $newBillNo[$field];
            //截取最新单据的时间
            $billTime = substr($billno, strlen($prev), 8);
            if ($billTime != $time) { //是否为今天的第一单
                $zancun = $prev . $time . '00001';
            } else {
                $billWaterNo = substr($billno, strlen($prev) + 8, 5);
                settype($billWaterNo, 'integer'); //将流水号转换成整型
                $billWaterNo++;                   //流水号自增
                //判断流水单号是否为5位
                if ($billWaterNo < 9999) {
                    $billWaterNo = str_pad($billWaterNo, 5, '0', STR_PAD_LEFT); //左侧填充0至5位
                }
                $zancun = $prev . $time . $billWaterNo;
            }
        }
        return $zancun;
    }
}

if (!function_exists('selectMenus_zuzhi')) {
    /**
     * 查询组织
     * @param int $catId 当前组织ID
     */
    function selectMenus_zuzhi($catId)
    {
        $res = Db::name('zuzhi')->field('id,pid')->select();
        $cateid = $catId;

        // 获取所有子组织ID
        $arr_all = getSubs1($res, $cateid);
        $arr_all[] = $cateid;
        $id = implode(',', $arr_all);

        // 查询符合条件的组织信息
        $select = Db::name('zuzhi')
            ->where('id', 'in', $id)
            ->field('id,pid,name')
            ->select();
        $select = selectMenus_res($select);
        return $select;
    }
}

if (!function_exists('getSubs1')) {
    /**
     * 获取所有子组织ID
     * @param array $categorys 组织信息数组
     * @param int $catId 当前组织ID
     * @param int $level 层级
     * @return array 所有子组织ID
     */
    function getSubs1($categories, $catId = 0, $level = 1)
    {
        $ids = []; // 用于存储所有子组织ID

        foreach ($categories as $item) {
            if ($item['pid'] == $catId) {
                $ids[] = $item['id']; // 收集当前组织ID
                // 递归获取子组织ID
                $childIds = getSubs1($categories, $item['id'], $level + 1);
                if (!empty($childIds)) {
                    $ids = array_merge($ids, $childIds);
                }
            }
        }

        return $ids;
    }
}
if (!function_exists('selectMenus_res')) {

    /**
     * 处理组织信息，生成树形结构
     * @param array $res 组织信息数组
     * @return array 处理后的组织信息
     */
    function selectMenus_res($res)
    {
        if (empty($res)) {
            return [];
        }

        // 生成树形结构
        $tree = nodeTrees($res, $res[0]['pid']);
        $data = [];

        // 格式化树形结构
        foreach ($tree as $k => $v) {
            $name = $v['level'] == 0 ? '<b>' . $v['name'] . '</b>' : '├─' . $v['name'];
            $name = str_repeat("│　", $v['level']) . $name;
            $data[$k]['id'] = $v['id'];
            $data[$k]['name'] = $name;
        }

        return $data;
    }
}
if (!function_exists('nodeTrees')) {

    function nodeTrees($arr, $parentId = 0, $level = 0)
    {
        $tree = [];

        foreach ($arr as $item) {
            if ($item['pid'] == $parentId) {
                $item['level'] = $level;
                $tree[] = $item;
                // 递归构建子树
                $children = nodeTrees($arr, $item['id'], $level + 1);
                if (!empty($children)) {
                    $tree = array_merge($tree, $children);
                }
            }
        }

        return $tree;
    }
}
if (!function_exists('pay_type')) {

    function pay_type($zuzhi)
    {
        if ($zuzhi['pay_channel_id']) {
            $pay_channel = Db::name('pay_channel')->whereIn('id', $zuzhi['pay_channel_id'])->where('switch', 1)->where('deletetime',)->select();
        } else {
            $zuzhi = Db::name('zuzhi')->where('id', $zuzhi['pid'])->find();
            $pay_channel = pay_type($zuzhi);
        }
        return $pay_channel;
    }
}
if (!function_exists('sendCmd')) {

//发送请求
    function sendCmd($url, $method = 'get', $data = [])
    {
//    dump($url);die;
        $curl = curl_init();                                      // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);                    // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);            // 对认证证书来源的检测
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);            // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); //解决数据包大不能提交
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);            // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);               // 自动设置Referer
        if ($method == 'post') {
            curl_setopt($curl, CURLOPT_POST, 1);           // 发送一个常规的Post请求
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);       // 设置超时限制防止死循
        curl_setopt($curl, CURLOPT_HEADER, 0);         // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回


        $tmpInfo = curl_exec($curl); // 执行操作

        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        $tmpInfo = json_decode($tmpInfo, true);
//     dump($tmpInfo);die;
        return $tmpInfo;   // 返回数据
    }
}
if (!function_exists('genghuan_one')) {

    function genghuan_one($id)
    {
        $datares = Db::name('list_three')->where('id', $id)->field('type,refund_time,refund_img,refund_money,refund_beizhu',1)->find();

        $datares['id'] = $datares['ids'];

        if (empty($datares['main_netrate']) && strlen($datares['main_netrate']) == 0) {
            unset($datares['main_netrate']);
        }
        if (empty($datares['main_netcost']) && strlen($datares['main_netcost']) == 0) {
            unset($datares['main_netcost']);
        }
        if (empty($datares['main_tongchoufee_heji']) && strlen($datares['main_tongchoufee_heji']) == 0) {
            unset($datares['main_tongchoufee_heji']);
        }
        if (empty($datares['main_xiaoguan_bili']) && strlen($datares['main_xiaoguan_bili']) == 0) {
            unset($datares['main_xiaoguan_bili']);
        }
        if (empty($datares['main_xiaoguan']) && strlen($datares['main_xiaoguan']) == 0) {
            unset($datares['main_xiaoguan']);
        }
        if (empty($datares['main_yunying_bili']) && strlen($datares['main_yunying_bili']) == 0) {
            unset($datares['main_yunying_bili']);
        }
        if (empty($datares['main_yunying']) && strlen($datares['main_yunying']) == 0) {
            unset($datares['main_yunying']);
        }
        if (empty($datares['main_tongchoujingfee_heji']) && strlen($datares['main_tongchoujingfee_heji']) == 0) {
            unset($datares['main_tongchoujingfee_heji']);
        }
        if (empty($datares['dong_fee']) && strlen($datares['dong_fee']) == 0) {
            unset($datares['dong_fee']);
        }
        //判断status状态
        $batch_state = $datares['batch_state']; //1-退单 2-改单（初审） 3-增单（初审、财务）
        unset($datares['batch_state']);
        unset($datares['status']);
        if ($batch_state == 1) {
            //退
            $datares['status'] = 6;
        }
        Db::name('list_one')->where('id', $datares['id'])->update($datares);
    }
}


